﻿using System;
using System.Data;
using System.Diagnostics.CodeAnalysis;

namespace clock
{
    class Clock
    {
        private DateTime currenttime;
        private DateTime alarm;
        private bool haveAlarm;
        public Clock()
        {
            setTime(DateTime.Now);
            haveAlarm = false;
        }
        public void setTime(DateTime time)
        {
            currenttime = time;
        }
        public string getTime()
        {
            return currenttime.ToString();
        }
        public void setAlarm(DateTime time)
        {   
            haveAlarm = true;
            alarm = time;
            while(alarm<currenttime)
            {
                alarm = alarm.AddDays(1);
            }
        }
        public void closeAlarm()
        {
            haveAlarm=false;
        }


        public delegate void TickEventHandler(string time);
        public event TickEventHandler TickEvent;
        public void onTickeEvent(string time)
        {
            if (TickEvent != null)
            {
                TickEvent(time);
            }
        }
        public delegate void AlarmEventHandler(string time);
        public event AlarmEventHandler AlarmEvent;
        public void onAlarmEvent(string time)
        {
            if (AlarmEvent != null)
            {
                AlarmEvent(time);
            }
        }

        public void run(object o)
        {
            currenttime=currenttime.AddSeconds(1);
            onTickeEvent(getTime());
            if(haveAlarm)
            {
                if (alarm <= currenttime)
                {   
                    closeAlarm();
                    onAlarmEvent(alarm.ToString());
                }
            }
        }

        public void start()
        {
            TimerCallback timerCallback = new TimerCallback(run);
            Timer timer = new Timer(timerCallback, null, 0, 1000);
        }
    }

    public class Test
    {
        static void Main(string[] args)
        {
            Clock clock = new Clock();
            clock.TickEvent += (string time) => Console.WriteLine("now is " + time);
            clock.AlarmEvent += (string time) => Console.WriteLine("alarm is invoke" + time);
            clock.setAlarm(DateTime.Now.AddSeconds(5));
            clock.start();
            Console.ReadKey();

        }
    }
}
